import socket
import json
from cryptography.fernet import Fernet

MCAST_GRP = '224.1.1.1' # 组播地址
MCAST_PORT = 5007 # 端口号
MESSAGE = b"Hello, World!" # 发送的消息

def encrypt(key, s):
    cipher = Fernet(key)
    return cipher.encrypt(s.encode()).decode()

with open("my_dict.bytes", "rb") as f:
    key = f.read()
# Opening JSON file
with open('sample.json', 'r') as openfile:
    # Reading from json file
    json_object = json.load(openfile)
    # Convert dict to string
data = json.dumps(json_object)
data = encrypt(key,data)
# 创建 UDP 套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

# 设置组播 TTL，这里设置为 1，表示仅限于本地网络
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)

# 发送数据报
sock.sendto(data.encode(), (MCAST_GRP, MCAST_PORT))